<?php


namespace app\admin\controller;


use app\admin\exception\AdminException;
use app\common\entity\FarmOrders;

use think\Request;
use think\Db;
use app\common\entity\UserPackage;
use app\common\entity\User;
use app\common\entity\AccountPos;
use think\facade\Env;
class Farmorder extends Admin
{
    /**
     * @power 内容管理|订单管理
     * @rank 0
     */
    public function index(Request $request) {
        $search = input('get.search');
        $type = input('get.type');
        $page = $request->param('page',1);
        $limit = $request->param('limit',15);
        $pageParam = [
            'page'=>$page,
            'limit'=>$limit
        ];
        $map = [];
        if ($type == 'mobile') {
            $map['u.mobile'] = $search;
            $pageParam['query']['search'] = $search;
            $pageParam['query']['type'] = $type;
        } elseif ($type == 'number') {
            $map['o.number'] = $search;
            $pageParam['query']['search'] = $search;
            $pageParam['query']['type'] = $type;
        }
        $lists = Db::name('pos_order')->alias('o')
            ->join('user u','u.id = o.user_id')
            ->join('user_package p','p.id = o.pos_id')
            ->field('o.*,u.mobile,p.name')
            ->where($map)
            ->order('create_time desc')
            ->paginate($limit,false,$pageParam);

        return $this->render('index',[
            'lists'=>$lists,
        ]);
    }


    /**
     * @power 内容管理|订单管理@确认发货
     */
    public function edit($order_number) {
        $query = FarmOrders::alias('o')->field('o.*,u.mobile as user_mobile');
        $query = $query->where('o.order_number',$order_number);
        $entity = $query->leftJoin("user u", 'u.id = o.user_id')
//            ->order('create_time', 'desc')
            ->find();

        if (!$entity) {
            $this->error('用户对象不存在');
        }

        return $this->render('edit', [
            'info' => $entity,
            'cate' => FarmOrders::getAllCate()
        ]);
    }

    /**
     * @power 内容管理|订单管理@发货
     */
    public function update(Request $request, $order_number) {
        $res = $this->validate($request->post(), 'app\admin\validate\GoodsOrders');

        if (true !== $res) {
            return json()->data(['code' => 1, 'message' => $res]);
        }

        $entity = $this->checkInfo($order_number);

        $service = new FarmOrders();
        $result = $service->updateGoodsOrders($entity, $request->post(),$service::TYPE_SEND);

        if (!$result) {
            throw new AdminException('保存失败');
        }

        return json(['code' => 0, 'toUrl' => url('index')]);
    }

    /*
     * 取消发货
     * */
    public function cancel(Request $request, $order_number){
        $entity = $this->checkInfo($order_number);

        $service = new FarmOrders();
        $result = $service->updateGoodsOrders($entity, $request->post(),$service::TYPE_CANCEL);
        if (!$result) {
            throw new AdminException('取消失败');
        }

        return json(['code' => 0, 'message' => 'success']);
    }

    private function checkInfo($order_number) {
        $entity = FarmOrders::where('order_number', $order_number)->find();
        if (!$entity) {
            throw new AdminException('对象不存在');
        }

        return $entity;
    }


    #套餐配置
    public function package()
    {
        $result = UserPackage::order('id asc')->select();
//        foreach ($result as &$v) {
//            $v['img'] = json_decode($v['img']);
//        }

        return $this->render('package', [
            'list' => $result,
            'package' => (new UserPackage())
        ]);
    }

    #套餐配置
    public function packageEdit($id)
    {
        $entity = UserPackage::where('id', $id)->find();
//        $entity['img'] = $entity['img'];
//        dump($entity);die;
        if (!$entity) {
            $this->error('用户对象不存在');
        }

        return $this->render('packageedit', [
            'info' => $entity,
            'package' => (new UserPackage())
        ]);
    }
    #套餐删除
    public function packagedelete($id)
    {
        $entity = UserPackage::where('id', $id)->delete();
//        $entity['img'] = $entity['img'];
//        dump($entity);die;

        if (!$entity) {
            return ['code' => 1, 'message' => '删除失败'];
        }
        return ['code' => 0, 'message' => '删除成功', 'toUrl' => url('package')];
    }

    #套餐添加配置
    public function packageAdd()
    {
        return $this->render('packageedit', [
            'package' => (new UserPackage())
        ]);
    }

    #添加配置
    public function packageSetadd(Request $request)
    {

        $img = $request->post('photo');
        $level_name = $request->post('name');

        $money = $request->post('money');
        $sort = $request->post('sort');
        if (!$img || !$level_name || !$money  ) {
            return ['code' => 1, 'message' => '缺少参数'];

        }

        $content = $request->post('content');
        $log = array(
            'img' => $img,
            'name' => $level_name,
            'money' => $money,
            'sort' => $sort,
            'update_time' => time(),
            'create_time' => time(),
            'content' => $content,
        );


        $result = UserPackage::insert($log);
        if (!$result) {
            return ['code' => 1, 'message' => '添加失败'];
        }
        return ['code' => 0, 'message' => '添加成功', 'toUrl' => url('package')];
    }

    #更改配置
    public function packageSetsave(Request $request)
    {
        $id = $request->get('id');
        $data = $request->post();

        $result = UserPackage::where('id', $id)->find();
        if (!$result) {
            throw new AdminException('操作错误');
        }
        $img = $request->post('photo');
        $level_name = $request->post('name');

        $money = $request->post('money');
        if (!$img || !$level_name || !$money ) {
            return ['code' => 1, 'message' => '缺少参数'];

        }

        $content = $request->post('content');
        if ($content) {
            $data['content'] = $content;

        }else{
            $data['content'] = $result['content'];

        }

        $img = $data['photo'];
        $log = array(
            'img' => $img,
            'name' => $data['name'],
            'money' => $data['money'],
            'sort' => $data['sort'],
            'content' => $data['content'],
            'number'=> $data['number'],
            'update_time' => time(),
        );

        $res = UserPackage::where('id', $id)->update($log);
        if (!$res) {
            return ['code' => 1, 'message' => '修改失败'];
        }
        return ['code' => 0, 'message' => '修改成功', 'toUrl' => url('package')];
    }


    #会员名下机器
    public function account_pos(Request $request){
        $order = 'preinstall desc';
        $where = '';
        $limit = $request->post('limit',15);
        $model = AccountPos::alias('p');
        if($request->param('keyword')) {
            switch ($request->param('type')) {
                case 'mobile':
                    $model->where('mobile','like','%'.$request->param('keyword').'%');
                    break;
            }
            $map['type'] = $request->param('type');
            $map['keyword'] = $request->param('keyword');
        }

        $list = User::field('preinstall,mobile,id as user_id')
            ->where('preinstall','>',0)
            ->where($where)
            ->order($order)
            ->group('id')
            ->paginate($limit, false, [
                'query' => isset($map) ? $map : []
            ])->each(function($item){
                $poss = AccountPos::where('user_id',$item['user_id'])->field('sn_id')->select()->toArray();
                $item['is_bind'] = Db::name('pos_sn')->where('sn_id','in',implode(',',array_column($poss,'sn_id')))->sum('is_bind');
                $item['sum_number'] = Db::name('pos_order')->where('user_id',$item['user_id'])->sum('number');
                return $item;
            });

        return $this->render('account_pos', [
            'list'=>$list,
            'queryStr' => isset($map) ? http_build_query($map) : '',
        ]);

    }




    #会员名下机器每日激活情况
    public function account_pos_day(Request $request){
        $id = $request->get('id');

        $list = Db::name('pos_sn')->alias('s')
            ->join('account_pos p','s.sn_id = p.sn_id')
            ->field('FROM_UNIXTIME(s.bind_time,"%Y-%m-%d") as time,sum(s.is_bind) as is_bind')
            ->where('p.user_id',$id)
            ->order('bind_time desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);

        return $this->render('account_pos_day', [
            'lists'=>$list
        ]);
    }
    #pos机编号
    public function snList(Request $request){

        $map['page'] = $request->param('page',1);
        $limit = $request->param('limit',15);
        $order = $request->param('order','id').' '.$request->param('sort','desc');
        if($request->param('order')){
            $map['s.order'] = $request->param('order');
            $map['s.sort'] = $request->param('sort');
        }
        $model = Db::name('pos_sn')->alias('s');

        if($request->param('bind_type')) {
            $map['bind_type'] = $request->param('bind_type');
            switch ($request->param('bind_type')) {
                case 'bind':
                    $model->where('s.is_bind', 1);
                    break;
                case 'not_bind':
                    $model->where('s.is_bind', 0);
                    break;
            }
        }
        if($request->param('p_bind_type')) {
            $map['p_bind_type'] = $request->param('p_bind_type');
            $account_pos = AccountPos::field('sn_id')->select()->toArray();
            switch ($request->param('p_bind_type')) {
                case 'bind':
                    $model->where('s.sn_id', 'in',implode(',',array_column($account_pos,'sn_id')));
                    break;
                case 'not_bind':
                    $model->where('s.sn_id', 'notin',implode(',',array_column($account_pos,'sn_id')));
                    break;
            }
        }
        if($request->param('keyword')) {
            switch ($request->param('type')) {
                case 'sn_id':
                    $map[$request->param('type')] = $request->param('keyword');
                    $model->where('s.sn_id','like','%' . $request->param('keyword') . '%');
                    break;
                case 'mobile':
                    $map[$request->param('type')] = $request->param('keyword');
                    $user = User::where('mobile',$request->param('keyword'))->value('pos');

                    $model->where('s.sn_id',$user);
                    break;
                case 'p_mobile':
                    $map[$request->param('type')] = $request->param('keyword');
                    $user = User::where('mobile',$request->param('keyword'))->value('id');
                    $sn_ids = AccountPos::where('user_id',$user)->select()->toArray();

                    $model->where('s.sn_id','in',implode(',',array_column($sn_ids,'sn_id')));
                    break;
            }
        }
        $list = $model->order($order)
            ->paginate($limit, false, [
                'query' => isset($map) ? $map : []
            ])->each(function($item){
                if($item['is_bind'] == 1){
                    $item['mobile'] = User::where('pos',$item['sn_id'])->value('mobile');
                }else{
                    $item['mobile'] = '';
                }
                $account_pos = Db::name('account_pos')->where('sn_id',$item['sn_id'])->find();
                if($account_pos){
                    $account_pos['mobile'] = User::where('id',$account_pos['user_id'])->value('mobile');
                    $item['account_pos'] = $account_pos;
                }else{
                    $item['account_pos'] = [];
                }
                return $item;
            });

        return $this->render('sn_list', [
            'list'=>$list
        ]);
    }
    #导入机器编号
    public function addSn(Request $request){

        //上传excel文件
        $file = $request->file('excel');
        if(!$file){
            $this->error('请上传文件！');
        }
        $info =  $file->validate(['size'=>1048576,'ext'=>'xlsx,xls'])->move(Env::get('root_path').'/uploads/excel/');
        if($info){
            $fileName = Env::get('root_path').'/uploads/excel/'.$info->getSaveName();
            $phpExcelObj = \PHPExcel_IOFactory::load($fileName);
            $sheet = $phpExcelObj->getSheet(0)->toArray();

        }else{
            $this->error('文件过大或格式不正确导致上传失败-_-!');
        }

        foreach($sheet as $key=>$value){
            $info = Db::name('pos_sn')->where('sn_id','like','%'.$value[0].'%')->find();
            
            if(!$info){
                Db::name('pos_sn')->insert([
                    'sn_id'=>$value[0],
                    'create_time'=>time(),
                ]);
            }

        }

        /*$model = new PosSn();
        $res = $model->insertAll($data,true);*/
        $this->success('搞定！');
        /*if($res){
            $this->success('搞定！');
        }else{
            $this->error('导入失败！');
        }*/
    }



    #绑定名下机器
    public function bindNext(Request $request){
        $id = $request->post('id');
        $posInfo = Db::name('pos_sn')->where('id',$id)->find();

        $user = User::where('mobile',$request->post('mobile'))->find();

        if(!$user){
            return json(['code' => 1, 'message' => '没有该用户']);
        }
        if($user['preinstall'] <= 0){
            return json(['code' => 1, 'message' => '该用户预安装不够']);
        }

        $account_pos = Db::name('account_pos')->where('sn_id',$posInfo['sn_id'])->find();
        if($account_pos['user_id']){
            return json(['code' => 1, 'message' => '该机器编码已经绑定']);
        }
        $model = new AccountPos();
        if($account_pos){
            $save = $model->where('id',$account_pos['id'])->update(['user_id'=>$user['id'],'sn_id'=>$posInfo['sn_id'],'create_time'=>time()]);
        }else{
            $save = $model->save(['user_id'=>$user['id'],'sn_id'=>$posInfo['sn_id'],'create_time'=>time()]);
        }
        User::where('mobile',$request->post('mobile'))->update(['preinstall'=>$user['preinstall']-1]);
        if($save){
            return json(['code' => 0, 'message' => '绑定成功']);
        }else{
            return json(['code' => 1, 'message' => '绑定失败']);
        }
    }


    public function unbindNext(Request $request){
        $id = $request->post('id');
        $posInfo = Db::name('pos_sn')->where('id',$id)->find();



        $account_pos = AccountPos::where('sn_id',$posInfo['sn_id'])->find();

        if(!$account_pos){
            return json(['code' => 1, 'message' => '该机器没有绑定会员名下']);
        }
        $save = AccountPos::where('id',$account_pos['id'])->update(['user_id'=>'','sn_id'=>$posInfo['sn_id'],'create_time'=>time()]);
        $user = User::where('id',$account_pos['user_id'])->find();
        User::where('id',$user['id'])->update(['preinstall'=>$user['preinstall']+1]);
        if($save){
            return json(['code' => 0, 'message' => '绑定成功']);
        }else{
            return json(['code' => 1, 'message' => '绑定失败']);
        }
    }

    #绑定机器编码
    public function bindSnId(Request $request){
        $id = $request->post('id');
        $posInfo = Db::name('pos_sn')->where('id',$id)->find();
        $sn_id = $posInfo['sn_id'];

        if(!$posInfo){
            return json(['code' => 1, 'message' => '没有该机器编码']);
        }elseif($posInfo['is_bind'] == 1){
            return json(['code' => 1, 'message' => '该机器编码已经绑定']);
        }
        $user = User::where('mobile',$request->post('mobile'))->find();

        if(!$user){
            return json(['code' => 1, 'message' => '没有该用户']);
        }

        if($user['is_active'] == 0){
            return json(['code' => 1, 'message' => '用户尚未激活']);
        }

        if($user['pos']){
            return json(['code' => 1, 'message' => '该用户已经绑定机器编码，如想更改请先解绑']);
        }


        $update = User::where('id',$user['id'])->update(['pos'=>$sn_id]);
        if($update){
            /* $active_reward = MywalletLog::where(['user_id'=>$user['id'],'types'=>14])->find();
             if(!$active_reward){
                 MywalletLog::addLog($this->userId,Config::getValue('active_reward'),3,'激活赠送活跃度',14,1);
                 $pid = User::where('id',$this->userId)->value('pid');
                 if($pid > 0){
                     $active_reward = MywalletLog::where(['user_id'=>$pid,'types'=>15,'remark'=>$this->userId])->find();
                     if(!$active_reward){
                         MywalletLog::addLog($pid,Config::getValue('find_active_reward'),3,$this->userId,15,1);
                     }
                 }
             }*/

            Db::name('pos_sn')->where('sn_id',$sn_id)->update(['is_bind'=>1,'bind_time'=>time()]);
            return json(['code' => 0, 'message' => '绑定成功']);
        }else{
            return json(['code' => 1, 'message' => '绑定失败']);
        }
    }
    #解绑机器编码
    public function unbindSnId(Request $request){
        $id = $request->post('id');
        $posInfo = Db::name('pos_sn')->where('id',$id)->find();
        $sn_id = $posInfo['sn_id'];
        $user = User::where('pos','like','%'.$sn_id.'%')->find();

        if(!$user){
            return json(['code' =>1, 'message' => '没有该用户']);
        }

        if($user['is_active'] == 0){
            return json(['code' => 1, 'message' => '请先激活']);
        }

        if(!$user['pos']){
            return json(['code' => 1, 'message' => '该用户已经解绑，请不要重复提交']);
        }

        $update = User::where('id',$user['id'])->update(['pos'=>'']);
        if($update){
            Db::name('pos_sn')->where('sn_id',$user['pos'])->update(['is_bind'=>0,'bind_time'=>time()]);
            /*$act = Mywallet::where(['user_id'=>$user['id']])->value('act');
            if($act){
                MywalletLog::addLog($this->userId,$act,3,'解绑扣除',17,2);
            }*/
            return json(['code' => 0, 'message' => '解绑成功']);
        }else{
            return json(['code' => 1, 'message' => '解绑失败']);
        }
    }

}